package com.tlgen.coopera.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import static com.tlgen.coopera.constant.Constants.DOWNLOAD_FILE_PATH;
import static com.tlgen.coopera.constant.Constants.READ_FILE_PATH;

public class FileUtils {

    /**
     * 读取文件内容
     *
     * @param file
     * @return
     */
    public static String readFile(File file) {
        String text = "";
        String encoding = "utf-8";
        try (InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
             BufferedReader bufferedReader = new BufferedReader(read)) {
            //判断文件是否存在
            if (file.isFile() && file.exists()) {
                String lineTxt;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    text += lineTxt + "\n";
                }
            } else {
                throw new RuntimeException("找不到指定的文件!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return text;
    }

    /**
     * 创建文件并写入内容
     */
    public static void createFile(String content) {
        try {
            File file = new File(READ_FILE_PATH);
            // 清空文件内容,  new FileWriter(file) 即使没有文件也会创建一个虚拟的文件
            FileWriter fileWriter = new FileWriter(file);
            fileWriter.write("");
            fileWriter.flush();
            fileWriter.close();
            // 写入内容
            BufferedWriter w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), "UTF-8"));
            w.write(content);
            w.flush();
            w.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据网络 url 下载文件到本地
     * @param downloadUrl
     */
    public static void download(String downloadUrl) {
        File outputPath = new File(DOWNLOAD_FILE_PATH); // 替换为要保存到本地的文件路径
        try {
            File dir = outputPath.getParentFile();
            if (!dir.exists()) {
                // 创建文件夹
                dir.mkdirs();
            }
            // 创建文件
            outputPath.createNewFile();
            URL url = new URL(downloadUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = new BufferedInputStream(connection.getInputStream());
                FileOutputStream outputStream = new FileOutputStream(outputPath);
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                outputStream.close();
                inputStream.close();
//                System.out.println("文件已成功下载到: " + outputPath);
            } else {
//                System.out.println("无法下载文件, HTT P响应码: " + connection.getResponseCode());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 比较两个文件的 md5 是否相同
     * @param file1Path
     * @param file2Path
     * @return
     */
    public static boolean compareFilesByMD5(String file1Path, String file2Path) {
        MessageDigest digest1 = null;
        MessageDigest digest2 = null;
        try {
            FileInputStream fis1 = new FileInputStream(new File(file1Path));
            FileInputStream fis2 = new FileInputStream(new File(file2Path));
            digest1 = getFileMD5(fis1);
            digest2 = getFileMD5(fis2);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Arrays.equals(digest1.digest(), digest2.digest());
    }

    /**
     * 获取文件的 md5
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static MessageDigest getFileMD5(InputStream inputStream) throws IOException {
        try (BufferedInputStream bis = new BufferedInputStream(inputStream)) {
            byte[] buffer = new byte[8192];
            int bytesRead;
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            while ((bytesRead = bis.read(buffer)) != -1) {
                messageDigest.update(buffer, 0, bytesRead);
            }
            return messageDigest;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("无法获取MD5算法", e);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }

    /**
     * 复制文件
     *
     * @param sourceFilePath
     * @param targetFilePath
     * @throws IOException
     */
    public static void copyFile(String sourceFilePath, String targetFilePath) {
        try {
            File sourceFile = new File(sourceFilePath);
            File targetFile = new File(targetFilePath);
            FileInputStream inputStream = new FileInputStream(sourceFile);
            FileOutputStream outputStream = new FileOutputStream(targetFile);
            byte[] buffer = new byte[4096];
            int length = 0;
            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }
            inputStream.close();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
